package com.etouch.security.controller;

import com.etouch.security.util.PhoneCodeUntil;
import com.etouch.security.util.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
@Slf4j
@Api(tags = "短信接口")
public class SmsController {

    private static final String LOGIN_CODE = "code:login:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiOperation("发送短信验证码")
    @RequestMapping(value = "/code",method = RequestMethod.POST)
    public String sms(String phone, HttpServletRequest request) {
        HttpSession session = request.getSession();
        int smsCode = (int) Math.ceil(Math.random() * 9000 + 1000);
        Map<String, Object> map = new HashMap<>(16);
        map.put("phone", phone);
        map.put("smsCode", smsCode);
        session.setAttribute("smsLogin", map);
        log.info("{}：为 {} 设置短信验证码：{}", session.getId(), phone, smsCode);
        return "你的手机号"+phone+"验证码是"+smsCode;
    }

    @ApiOperation("发送登陆短信验证码(王炜)")
    @RequestMapping(value = "/loginCode",method = RequestMethod.POST)
    public ResultUtils loginCode(String phone) {
        //1. 调用你那的发送短信的工具类
        String smsCode = PhoneCodeUntil.getRandomString(4);
        //存入redis中, 有效期两分钟
        redisTemplate.opsForValue().set(LOGIN_CODE,smsCode,120, TimeUnit.SECONDS);
        log.info("发送给手机号: "+phone+" 的验证码为: "+smsCode);
        return ResultUtils.success("发送成功", smsCode);
    }
}
